package com.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

import com.alibaba.fastjson.JSONObject;


public class GetPlaceByIp {
	public static void main(String[] args) throws MalformedURLException, IOException {
		JSONObject json =  readFromUrl("http://api.map.baidu.com/location/ip?ak=xIqVDHIOVyGuppRMSAlOS2mwQdwwnOzX");
		System.out.println(((JSONObject) json.get("content")).get("address"));
	}
    
	private static JSONObject readFromUrl(String url) throws MalformedURLException, IOException {
		InputStream input = new URL(url).openStream();
		try{
			BufferedReader rd = new BufferedReader(new InputStreamReader(input, Charset.forName("gb2312")));
			String jsonText =readAll(rd);
			JSONObject json = new JSONObject();
			JSONObject object = json.parseObject(jsonText);
			return object;
		}finally{
			input.close();
		}
	}

	private static String readAll(Reader rd) throws IOException {
		StringBuilder stringBuilder = new StringBuilder();
		int cp;
	    while ((cp = rd.read()) != -1) {
	    	stringBuilder.append((char) cp);
	    }
	    return stringBuilder.toString();
	}

}
